﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;
using LiteBlog.Common;
using LiteBlog.Common.Entities;
using LiteBlog.Repositories.Contracts;
using LiteBlog.Common.Enums;
using LiteBlog.Repositories.Framework;
using LiteBlog.Repositories.Common;

namespace LiteBlog.Repositories
{
    public class PageRepository : DataAccess, IPageRepository
    {
        private static string _dataPath;
        private static string _path = string.Empty;
        private PageMetaRepository _pageMeta;

        public PageRepository(IDataContext context, IXmlHelper xmlHelper) : base(context, xmlHelper)
        {
            _dataPath = context.DataPath;
            _pageMeta = new PageMetaRepository(context, xmlHelper);
        }  

        public Page Load(string fileId)
        {
            string filePath = GetPath(fileId);
            Page page = new Page();
            page.FileId = fileId;

            XDocument doc = XDocument.Load(string.Format(filePath, fileId));
            XElement elem = doc.Root;
            page.Title = (string)elem.Attribute("Title");
            page.Body = elem.Value;

            // Fill page meta
            var pageMeta = _pageMeta.Get(fileId);
            page.Published = pageMeta.Published;
            page.IncludeInHeaderMenu = pageMeta.IncludeInHeaderMenu;

            return page;
        }

        public void Save(Page page)
        {
            if (_pageMeta.Get(page.FileId)==null)
                _pageMeta.Create(page);
            else
                _pageMeta.Update(page);
            XDocument doc = XDocument.Parse("<Page></Page>");
            doc.Root.SetAttributeValue("FileId", page.FileId);
            doc.Root.SetAttributeValue("Title", page.Title);
            doc.Root.SetValue(page.Body ?? string.Empty);
            doc.Save(GetPath(page.FileId));
        }

        public List<Page> GetPages()
        {
            return _pageMeta.Get();
        }

        public void Delete(string fileId)
        {
            string filePath = GetPath(fileId);
            if (File.Exists(filePath))
                File.Delete(filePath);
            _pageMeta.Delete(fileId);
        }

        public bool IsUniqueId(string fileId)
        {
            return _pageMeta.Get(fileId)==null;
        }

        private string GetPath(string id)
        {
            return _context.GetPath(DataStoreType.Page, id);
        }
    }
}
